<?php
/**
 * EventRepo.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-16 03:22:59
 * @modified    2023-02-16 03:22:59
 *
 */

namespace App\Repositories\Customer;

use App\Models\Event;
use App\Models\Product;

class EventRepo
{
    const TYPE_REQUEST = 'request'; // 服务请求
    const TYPE_REPAIR = 'repair'; // 客户报修
    const TYPE_ORDER = 'order'; // 服务订单
    const TYPE_MAINTENANCE = 'maintenance'; // 维保服务
    const TYPE_MANAGE = 'manage'; // 项目管理
    const TYPE_COMPLAIN = 'complain'; // 意见投诉

    const STATUS_UN_DISTRIBUTE = 'un_distribute'; // 待分配
    const STATUS_DISTRIBUTED = 'distribute'; // 已分配(未完成)
    const STATUS_COMPLETED = 'completed'; // 已完成
    const STATUS_CLOSED = 'closed'; // 已关闭(转工单后自动关闭)

    const CREATED_TYPE_CUSTOMER = 'customer';
    const CREATED_TYPE_USER = 'user';

    public static function params()
    {
        return [
            'types' => [
                ['code' => self::TYPE_REQUEST, 'title' => '服务请求'],
                ['code' => self::TYPE_REPAIR, 'title' => '客户报修'],
                ['code' => self::TYPE_ORDER, 'title' => '服务订单'],
                ['code' => self::TYPE_MAINTENANCE, 'title' => '维保服务'],
                ['code' => self::TYPE_MANAGE, 'title' => '项目管理'],
                ['code' => self::TYPE_COMPLAIN, 'title' => '意见投诉'],
            ],
            'create_types' => [
                ['code' => self::CREATED_TYPE_CUSTOMER, 'title' => '客户自助'],
                ['code' => self::CREATED_TYPE_USER, 'title' => '客服录入'],
            ],
            'status' => [
                ['code' => self::STATUS_UN_DISTRIBUTE, 'title' => '待分配'],
                ['code' => self::STATUS_DISTRIBUTED, 'title' => '未完成'],
                ['code' => self::STATUS_COMPLETED, 'title' => '已完成'],
                ['code' => self::STATUS_CLOSED, 'title' => '已关闭']
            ],
            'unusual_status' => [

            ]
        ];
    }

    public static function param_codes()
    {
        $params = self::params();
        return collect($params)->pluck('code')->toArray();
    }

    public static function store()
    {
        $eventData = self::eventData();
        $main = $eventData['main'];
        $images = $eventData['images'];
        $managerPhone = $eventData['manager_phone'];
        $event = new Event();
        $event->fill($main);
        $event->saveOrFail();

        $eventImages = [];
        foreach ($images as $image) {
            $eventImages[] = new Event\Image([
                'img' => $image
            ]);
        }

        $event->images()->saveMany($eventImages);

        // 发送通知、添加operation log

    }

    private static function eventData()
    {
        $requestData = request()->getContent();
        $requestArr = json_decode($requestData, true);

        $type = $requestArr['type'] ?? '';
        $paramCodes = self::param_codes();
        if (!in_array($type, $paramCodes)) {
            throw new \Exception(t('event.invalid_type'));
        }

        $productId = $requestArr['product_id'] ?? 0;

        $product = Product::find($productId);
        if (empty($product)) {
            throw new \Exception(t('event.invalid_product_id'));
        }

        $productCustomerId = $product->customer_id;

        $customerUser = registry('customer_user');
        $customerId = $customerUser->customer_id;
        if ($customerId != $productCustomerId) {
            // throw new \Exception(t('event.invalid_product_customer'));
        }
        $requestImages = $requestArr['images'] ?? [];
        $images = [];
        foreach ($requestImages as $requestImage) {
            $requestImage = trim($requestImage);
            if (!$requestImage) {
                continue;
            }
            $images[] = $requestImage;
        }

        $main = [
            'event_number' => self::generateNumber(0),
            'type' => $type,
            'customer_id' => $customerId,
            'customer_user_id' => $customerUser->id,
            'product_id' => $productId,
            'created_type' => self::CREATED_TYPE_CUSTOMER,
            'created_by' => $customerUser->id,
            'description' => $requestArr['description'] ?? '',
            'status' => self::STATUS_UN_DISTRIBUTE
        ];
        $managerPhone = $customerUser->customer->department->manager->telephone ?? '';
        return [
            'main' => $main,
            'manager_phone' => $managerPhone,
            'images' => $images
        ];
    }

    public static function generateNumber($id)
    {
        if ($id) {
            $event = Event::findOrFail($id);
            return $event->event_number;
        }
        $number = 'CVS' . date('ymd') . rand(100000, 999999);
        $eventsCount = Event::byNumber($number)->count();
        if ($eventsCount) {
            return self::generateNumber($id);
        }
        return $number;
    }
}